package com.gusha.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusha.dao.ProcessingOrderDao;
import com.gusha.model.ProcessingOrder;
import com.gusha.model.SysProcessing;
import com.gusha.model.User;
@Service
@Transactional
public class ProcessingOrderService {
	@Autowired
	private ProcessingOrderDao processingOrderDao;

	public Page<ProcessingOrder> findAll(Pageable pageable, ProcessingOrder ProcessingOrder) {

		@SuppressWarnings("serial")
		Page<ProcessingOrder> result = processingOrderDao.findAll(new Specification<ProcessingOrder>() {
			@Override
			public Predicate toPredicate(Root<ProcessingOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (ProcessingOrder.getId() != null) {
					list.add(cb.equal(root.get("id").as(BigInteger.class), ProcessingOrder.getId()));
				}
				if (ProcessingOrder.getUserId() != null) {
					list.add(cb.equal(root.get("userId").as(User.class), ProcessingOrder.getUserId()));
				}
				if (ProcessingOrder.getProcessingId() != null) {
					list.add(cb.equal(root.get("processingId").as(SysProcessing.class), ProcessingOrder.getProcessingId()));
				}
				if (ProcessingOrder.getBuyNum() != null) {
					list.add(cb.equal(root.get("buyNum").as(BigInteger.class), ProcessingOrder.getBuyNum()));
				}
				if (ProcessingOrder.getState() != null) {
					list.add(cb.equal(root.get("state").as(BigInteger.class), ProcessingOrder.getState()));
				}
				if (ProcessingOrder.getAddTime() != null) {
					list.add(cb.equal(root.get("addTime").as(Date.class), ProcessingOrder.getAddTime()));
				}

				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		}, pageable);
		return result;
	}
}
